package xyz.jcat.mybatis;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;

import java.util.Date;
import java.util.Objects;

/**
 * TODO
 * mybatis-plus自动填充字段值
 */
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        setValues(DBConst.PO_FIELD_CREATE_TIME, now, metaObject, FieldFill.INSERT);
        setValues(DBConst.PO_FIELD_UPDATE_TIME, now, metaObject, FieldFill.INSERT);
//        setFieldValByName(DBConst.PO_FIELD_CREATOR, userId, metaObject, FieldFill.INSERT);
//        setFieldValByName(DBConst.PO_FIELD_UPDATER, userId, metaObject, FieldFill.INSERT);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setValues(DBConst.PO_FIELD_UPDATE_TIME, new Date(), metaObject, FieldFill.UPDATE);
//        setFieldValByName(DBConst.PO_FIELD_UPDATER, getUserId(), metaObject, FieldFill.UPDATE);
    }

    private MetaObjectHandler setValues(String fieldName, Object fieldVal, MetaObject metaObject, FieldFill fieldFill) {
        if (Objects.nonNull(fieldVal)) {
            Object oldValue = getFieldValByName(fieldName, metaObject);
            //新增的时候如果原数据有值则不设置默认值
            if (Objects.equals(fieldFill, FieldFill.INSERT) && oldValue != null) {
                // not handle
            } else {
                setFieldValByName(fieldName, fieldVal, metaObject);
            }
        }
        return this;
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInnerInterceptor paginationInnerInterceptor() {
        return new PaginationInnerInterceptor();
    }

}
